package com.gitee.openviducn.inspector.domain.vo.response.openvidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.gitee.openviducn.inspector.domain.vo.response.BaseResponse;
import io.openvidu.java.client.Session;
import io.swagger.annotations.ApiModel;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: https://gitee.com/wesleyOne
 * @Date: 03.03 2020
 */
@ApiModel(value = "Session信息")
@Getter
@Setter
public class SessionVO extends BaseResponse {
    private static final long serialVersionUID = -1247860112902466346L;

    private String sessionId;
    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    private Date createdAt;
    private List<ConnectionVO> connections = new ArrayList<>();
    private Boolean recording = false;
    private Integer connectCount;
    private Long pubCount;
    private Long subCount;

    /**
     * io.openvidu.java.client.SessionProperties
     */
    private String mediaMode;
    private String recordingMode;
    private String defaultOutputMode;
    private String defaultRecordingLayout;
    private String defaultCustomLayout;
    private String customSessionId;

    public static SessionVO build(Session session) {
        SessionVO vo = new SessionVO();
        vo.setSessionId(session.getSessionId());
        vo.setCreatedAt(new Date(session.createdAt()));
        vo.setCustomSessionId(session.getProperties().customSessionId());
        vo.setRecording(session.isBeingRecorded());
        vo.setMediaMode(session.getProperties().mediaMode().name());
        vo.setRecordingMode(session.getProperties().recordingMode().name());
        vo.setDefaultOutputMode(session.getProperties().defaultOutputMode().name());
        vo.setDefaultRecordingLayout(session.getProperties().defaultRecordingLayout().name());
        vo.setDefaultCustomLayout(session.getProperties().defaultCustomLayout());
        List<ConnectionVO> connections = new ArrayList<>();
        session.getActiveConnections().forEach(con -> connections.add(ConnectionVO.build(con)));
        vo.setConnections(connections);
        vo.setConnectCount(connections.size());
        vo.setPubCount(connections.stream().mapToLong(c -> c.getPublishers().size()).sum());
        vo.setSubCount(connections.stream().mapToLong(c -> c.getSubscribers().size()).sum());
        return vo;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
